package com.biubiu.rotationchart;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.interpolator.view.animation.LinearOutSlowInInterpolator;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.widget.ViewPager2;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageSwitcher;
import android.widget.ImageView;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final int MESSAGE_LOOP = 1;
    private ViewPager2 mViewPager2;
    private ViewPagerAdapter adapter;
    private int[] colorArray = new int[]{R.drawable.item01,R.drawable.item02,R.drawable.item03,R.drawable.item04};
    private int loop_ms = 3000;
    private int loop_duration = 2000;
    private boolean isScaleAnimation = true;
    private List<String> list;
    private MyImageView mImgBg;

    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            if (msg.what == MESSAGE_LOOP) {
                if (mViewPager2.getCurrentItem() < Short.MAX_VALUE - 1) {
                    mViewPager2.setCurrentItem(mViewPager2.getCurrentItem() + 1, true);
                    setCurrentItem(mViewPager2);
                    handler.removeMessages(MESSAGE_LOOP);
                    sendEmptyMessageDelayed(MESSAGE_LOOP, getLoop_ms());
                }
            }
        }
    };
    private int currentIndex;
    private boolean isFistTime = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        list = new ArrayList<>();
        list.add("页面一");
        list.add("页面二");
        list.add("页面三");
        list.add("页面四");
        mImgBg = findViewById(R.id.img_bg);
        mImgBg.setInAnimation(AnimationUtils
                .loadAnimation(MainActivity.this, R.anim.alpha_in));
        mImgBg.setOutAnimation(AnimationUtils
                .loadAnimation(MainActivity.this, R.anim.alpha_out));
        mViewPager2 = findViewById(R.id.viewpager2);
        adapter = new ViewPagerAdapter(this, list);
        mViewPager2.setAdapter(adapter);
        mViewPager2.setCurrentItem(adapter.getItemCount()/2,false);
        mViewPager2.setOffscreenPageLimit(1);//预加载（左右各）一页

        setListener();
        startLoop();
    }

    private void setListener() {
        mViewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels);
                final int index = position % list.size();
                //Log.i("onPageScrolled", "index = " + index + ", currentIndex = " + currentIndex);
                Log.i("onPageScrolled", "index = " + index + ", positionOffset = " + positionOffset + ", positionOffsetPixels = " + positionOffsetPixels);
                //mImgBg.setBackgroundResource(colorArray[index]);
                if (currentIndex != index) {
                    currentIndex = index;
                    mImgBg.setImageResource(colorArray[currentIndex]);
                }

                //轮播图动画
                if (isScaleAnimation) {
                    ImageView imageView;
                    if (positionOffset == 0f) {
                        if (adapter.getPrimaryItem(mViewPager2.getCurrentItem()) != null) {
                            imageView = (ImageView) adapter.getPrimaryItem(mViewPager2.getCurrentItem());
                            if (imageView != null) {
                                bigIndex = mViewPager2.getCurrentItem();
                                enLargeView(imageView);
                            }
                        }
                    } else {
                        if (bigIndex != -1) {
                            if (adapter.getPrimaryItem(bigIndex) != null) {
                                imageView = (ImageView) adapter.getPrimaryItem(bigIndex);
                                narrowView(imageView);
                            }

                        }
                    }
                }
            }
        });

        mViewPager2.getChildAt(0).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        stopLoop();
                        break;
                    case MotionEvent.ACTION_UP:
                        startLoop();
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
    }

    public void stopLoop() {
        handler.removeMessages(MESSAGE_LOOP);
    }

    public void startLoop() {
        handler.removeMessages(MESSAGE_LOOP);
        handler.sendEmptyMessageDelayed(MESSAGE_LOOP, getLoop_ms());
    }

    public int getLoop_ms() {
        if (loop_ms < 1500)
            loop_ms = 1500;
        return loop_ms;
    }

    public void setCurrentItem(ViewPager2 pager) {
        int[] previousValue = {0};
        int pagePxWidth = pager.getWidth();
        int pxToDrag = pagePxWidth;
        final ValueAnimator animator = ValueAnimator.ofInt(0, pxToDrag);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int currentValue = (int) animation.getAnimatedValue();
                float currentPxToDrag = (float) (currentValue - previousValue[0]);
                pager.fakeDragBy(-currentPxToDrag);
                previousValue[0] = currentValue;
            }
        });
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                pager.beginFakeDrag();
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                pager.endFakeDrag();
            }

            @Override
            public void onAnimationCancel(Animator animation) { }

            @Override
            public void onAnimationRepeat(Animator animation) { }
        });
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        animator.setDuration(1500);
        animator.start();
    }


    AnimatorSet animatorSetsuofang = new AnimatorSet();
    ObjectAnimator scaleX;
    ObjectAnimator scaleY;

    AnimatorSet animatorSmall = new AnimatorSet();
    ObjectAnimator smallScaleX;
    ObjectAnimator smallScaleY;
    private int bigIndex;
    float smallScaleValue = 1.0f;
    float bigScaleValue = 1.2f;
    /**
     * 放大View
     *
     * @param view
     */
    public void enLargeView(final View view) {
        if (view.getScaleX() == smallScaleValue) {
            scaleX = ObjectAnimator.ofFloat(view, "scaleX", smallScaleValue, bigScaleValue);
            scaleY = ObjectAnimator.ofFloat(view, "scaleY", smallScaleValue, bigScaleValue);
            animatorSetsuofang.setDuration(500);
            animatorSetsuofang.setInterpolator(new LinearInterpolator());
            animatorSetsuofang.play(scaleX).with(scaleY);//两个动画同时开始
            animatorSetsuofang.start();
            animatorSetsuofang.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    //view.clearAnimation();
                    //animatorSetsuofang.removeAllListeners();
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
        }
    }

    /**
     * 缩小View
     *
     * @param view
     */
    public void narrowView(final View view) {
        if (view != null && view.getScaleX() == bigScaleValue) {
            smallScaleX = ObjectAnimator.ofFloat(view, "scaleX", bigScaleValue, smallScaleValue);
            smallScaleY = ObjectAnimator.ofFloat(view, "scaleY", bigScaleValue, smallScaleValue);
            animatorSmall.setDuration(100);
            animatorSmall.setInterpolator(new LinearInterpolator());
            animatorSmall.play(smallScaleX).with(smallScaleY);//两个动画同时开始
            animatorSmall.start();
            bigIndex = -1;
            animatorSmall.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }
                @Override
                public void onAnimationEnd(Animator animation) {
                    //view.clearAnimation();
                    //animatorSmall.removeAllListeners();
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
        }
    }
}